package com.wlanauth.web.core;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.wlanauth.domain.manage.Operator;
import com.wlanauth.domain.manage.Role;
import com.wlanauth.domain.manage.SystemResource;

/**
 * 检查会话是否存在，如果不存在则要求客户端登录。
 * 
 * 本拦截器在struts.xml中配置成不拦截LoginAction。
 * 
 * @author zz
 *
 */
public class LoginInterceptor extends MethodFilterInterceptor {

	private static final long serialVersionUID = 792719850007191483L;

	@Override
	public String doIntercept(ActionInvocation invocation) throws Exception {
		final ActionContext context = invocation.getInvocationContext();
		
		// http://struts.apache.org/2.x/struts2-core/apidocs/constant-values.html
		HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
		HttpSession session = request.getSession();
		Operator oper = (Operator) session.getAttribute(SystemConstants.SESSION_OPER_KEY);
		
		if (oper == null) {
			request.setAttribute("msg", "您尚未执行系统登录，或因较长时间未使用系统而自动退出，请重新登录");
			return SystemConstants.RESULT_NO_SESSION;
		} else {
			Role role = oper.getRole();
			if(role != null&&role.getSystemResources()!=null) {
				String className = invocation.getAction().getClass().getName();
				String method = invocation.getProxy().getMethod();
				Set<SystemResource> actions = role.getSystemResources();
				for(SystemResource action:actions){
					String code = className+"."+method;
//					if(code.matches(action.getCode())){
//						return invocation.invoke();
//					}
					if(action.getValue()!=null&&code.matches(action.getValue())){
						return invocation.invoke();
					}
				}
			}
		}
		request.setAttribute("msg", "对不起,您无权操作!");
		return SystemConstants.RESULT_NO_SESSION;
		
	}

}
